package com.cdwm.mrp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdwm.mrp.common.tools.Doc2Html;
import com.cdwm.mrp.common.tools.LayuiResponse;
import com.cdwm.mrp.common.tools.PdfUtil;
import com.cdwm.mrp.common.tools.UploadPathUtil;
import com.cdwm.mrp.domain.po.Customer;
import com.cdwm.mrp.domain.po.InterfaceDoc;
import com.cdwm.mrp.domain.po.Project;
import com.cdwm.mrp.mapper.CustomerMapper;
import com.cdwm.mrp.mapper.InterfaceDocMapper;
import com.cdwm.mrp.mapper.ProjectMapper;
import com.cdwm.mrp.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/3
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {
    private static final ArrayList<String> systemRoot = UploadPathUtil.getSystemRoot();

    @Autowired(required = false)
    private ProjectMapper projectMapper;

    @Autowired(required = false)
    private CustomerMapper customerMapper;

    @Autowired(required = false)
    private InterfaceDocMapper interfaceDocMapper;

    @Override
    public LayuiResponse<?> getProjectList(Project project, Integer page, Integer limit) {

        Page<Project> pager = new Page<>(page, limit);
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(
                Objects.nonNull(project.getProjectName())&& !Objects.equals("",project.getProjectName()),
                "project_name",project.getProjectName()).
                    eq(Objects.nonNull(project.getProjectContact())&& !Objects.equals("",project.getProjectContact()),
                            "project_contact",project.getProjectContact());
        Page<Project> projectPage = projectMapper.selectPage(pager, queryWrapper);

        // 封装客户
        projectPage.getRecords().forEach((pro)->{
            Customer customer = customerMapper.selectById(pro.getCustomerId());
            pro.setCustomer(customer);
        });
        // 封装接口路径
        projectPage.getRecords().forEach((pro)->{
            QueryWrapper<InterfaceDoc> wrapper = new QueryWrapper<InterfaceDoc>();
            wrapper.eq("project_id",pro.getId());
            pro.setInterfaceDocs(interfaceDocMapper.selectList(wrapper));
        });


        return LayuiResponse.ok(projectPage.getRecords(),projectPage.getTotal());

    }

    /**
     * 上传接口文档
     * @param file
     * @param req
     * @param id
     * @return
     */
//    @Override
//    public Boolean uploadInterfaceWord(MultipartFile file, HttpServletRequest req, Integer id) {
//
//        //使用UUID生成唯一标识文件名
//        String randomNumber = UUID.randomUUID().toString().replace("-", "");
//        //获取文件的原始名
//        String oldFilename = file.getOriginalFilename();
//        //获取文件后缀 .pdf
//        String extension = oldFilename.substring(oldFilename.lastIndexOf("."));
//        //生成新的文件名
//        String newFileName = randomNumber + extension;
//
//        ArrayList<String> systemRoot = UploadPathUtil.getSystemRoot();
//
//        File dateDir = new File(systemRoot.get(0));
//        if (!dateDir.exists()) {
//            //判断目录是否存在，不存在则直接创建
//            dateDir.mkdirs();
//        }
//        try {
//            file.transferTo(new File(dateDir, newFileName));
//        } catch (IOException e) {
//            e.printStackTrace();
//            return false;
//        }
//
//
//        // 虚拟路径
//        String invented_address = null;
//
//        // 文件后缀,方便前端判断
//        String fileSuffix = null;
//
//        if (extension.equals(".pdf")){
//            // 上传文件为.pdf后缀的虚拟访问路径
//            invented_address  = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/static/document/" + newFileName;
//            // 添加后缀
//            fileSuffix = extension.substring(extension.indexOf(".") + 1);
//        }
//        // doc docx转pdf在保存地址到数据库中
//        else if (extension.equals(".doc") || extension.equals(".docx")) {
//            // 转换之后的pdf文件
//            String newPdfName = randomNumber+".pdf";
//            PdfUtil.doc2Pdf(new File(dateDir, newFileName), new File(dateDir, newPdfName), extension);
//            // 转换之后的pdf文件虚拟路径
//            invented_address  = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/static/document/" + newPdfName;
//            // 添加后缀
//            fileSuffix = extension.substring(extension.indexOf(".") + 1);
//        }
//
//
//        InterfaceDoc interfaceDoc = new InterfaceDoc();
//        interfaceDoc.setProjectId(id);
//        interfaceDoc.setUrlAddress(invented_address);
//        interfaceDoc.setSuffix(fileSuffix);
//        interfaceDoc.setDocName(oldFilename);
//        interfaceDocMapper.insert(interfaceDoc);
//
//        return true;
//    }

    /**
     * 上传接口文档
     * @param multipartFile
     * @param req
     * @param id
     * @return
     */
    @Override
    public Boolean uploadInterfaceWord(MultipartFile multipartFile, HttpServletRequest req, Integer id) throws Exception {
        //使用UUID生成唯一标识文件名
        String randomNumber = UUID.randomUUID().toString().replace("-", "");
        //获取文件的原始名
        String oldFilename = multipartFile.getOriginalFilename();
        //获取文件后缀 .pdf/.docx/.doc
        String extension = oldFilename.substring(oldFilename.lastIndexOf("."));
        //生成新的文件名
        String newFileName = randomNumber + extension;


        // 文档上传路径
        File documentUpload = new File(systemRoot.get(0));
        if (!documentUpload.exists()) {
            //判断目录是否存在，不存在则直接创建
            documentUpload.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(documentUpload, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }


        InputStream input = null;
        OutputStream out = null;

        // 虚拟路径
        String invented_address = null;

        // 文件后缀,方便前端判断
        String fileSuffix = null;

        // 构建doc和docx新的文件名
        String docAndDocxNewFileName =  randomNumber + ".html";

        if (extension.equals(".pdf")){
            // 上传文件为.pdf后缀的虚拟访问路径
            invented_address  = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/static/document/" + newFileName;
            // 添加后缀
            fileSuffix = extension.substring(extension.indexOf(".") + 1);
        } else

            // 在线预览
            //获取文件路径
            if (extension.equals(".docx")) {

                Doc2Html.docx2Html(systemRoot.get(0) + newFileName, systemRoot.get(0) + docAndDocxNewFileName);

                // 上传文件为.pdf后缀的虚拟访问路径
                invented_address  = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/static/document/" + docAndDocxNewFileName;
                // 添加后缀
                fileSuffix = extension.substring(extension.indexOf(".") + 1);

//                input = new FileInputStream(systemRoot.get(0) + docAndDocxNewFileName);
//                response.setContentType("text/html;charset=UTF-8");// 解决页面显示乱码
//                out = response.getOutputStream();
            } else if (extension.equals(".doc")) {
                Doc2Html.doc2Html(systemRoot.get(0) + newFileName, systemRoot.get(0) + docAndDocxNewFileName);

                // 上传文件为.pdf后缀的虚拟访问路径
                invented_address  = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/static/document/" + docAndDocxNewFileName;
                // 添加后缀
                fileSuffix = extension.substring(extension.indexOf(".") + 1);

//                input = new FileInputStream(systemRoot.get(0) + docAndDocxNewFileName);
//                response.setContentType("text/html;charset=UTF-8");// 解决页面显示乱码
//                out = response.getOutputStream();
            }

        InterfaceDoc interfaceDoc = new InterfaceDoc();
        interfaceDoc.setProjectId(id);
        interfaceDoc.setUrlAddress(invented_address);
        interfaceDoc.setSuffix(fileSuffix);
        interfaceDoc.setDocName(oldFilename);
        interfaceDocMapper.insert(interfaceDoc);

        return true;

//        if (extension.equals(".docx") || extension.equals(".doc")) {
//            FileInputStream fis = new FileInputStream(systemRoot.get(0) + docAndDocxNewFileName);
//            byte[] b = new byte[fis.available()];
//            if (out != null) {
//                if (input != null) {
//                    input.read(b);
//                    out.write(b);
//                } else {
//                    System.out.println("InputStream为空。。。");
//                }
//            } else {
//                System.out.println("OutputStream为空。。。");
//            }
//
//            out.flush();
//            input.close();
//            out.close();
//        }

    }
}
